﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR.Hubs;
using Microsoft.AspNet.SignalR;
using System.Threading.Tasks;


namespace ChatApplication.Models
{
    [HubName("chatHub")]
    public class ChatHub : Hub
    {
        private readonly int TimeoutInSeconds = 30;
        private readonly Chat chat;

        public ChatHub() : this(Chat.Instance) { }

        public ChatHub(Chat chat)
        {            
            this.chat = chat;
        }

        public void Join(string myName)
        {
            if (Chat.Clients.Where(x => x.Name.Equals(myName)).Count().Equals(0))
            {
                Chat.Clients.Add(new Client() { Name = myName, LastResponse = DateTime.Now, ConnectionId = this.Context.ConnectionId });
                SendMessageServer(string.Format("{0} entered the chat", myName));
                GetClients();
                Clients.Caller.Naam = myName;
            }
            else
                throw new Exception("This login is allready in use");
        }

        public override Task OnDisconnected()
        {
            var client = Chat.Clients.Where(x => x.ConnectionId == this.Context.ConnectionId).FirstOrDefault();
            string name = client != null ? client.Name : "unknwon";
            return Clients.All.leave(name, DateTime.Now.ToString());
        }

        
        private void GetClients()
        {
            chat.GetClients();
        }

        public void SendMessageServer(string message)
        {
            chat.SpreadMessage(message);
        }

        public void SendMessage(string message)
        {
            if (Chat.Clients.Where(x => x.Name.Equals(this.Clients.Caller.Naam)).Count() > 0)
                chat.SpreadMessage(string.Format("({0}) <b>{1}</b>: {2}", DateTime.Now.ToString("HH:mm"), this.Clients.Caller.Naam, message));            
        }
    }
}